#define _CRT_SECURE_NO_WARNINGS 1
#include"SList.h"
void SLInit(pSL ps) {
	ps->a = NULL;
	ps->capacity = ps->size = 0;

}

void SLDestroy(pSL ps) {
	ps->capacity = ps->size = 0;
	free(ps->a);
	ps->a = NULL;
}

void SLCheckCapacity(pSL ps) {
	if (ps->capacity == 0) {
		int Newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * Newcapacity);
		if (tmp == NULL) {
			perror("realloc fail");
			return;
		}
		ps->a = tmp;
		ps->capacity = Newcapacity;

	}
}
void SLPrint(pSL ps) {
	assert(ps);
	for (int i = 0; i < ps->size; i++) {
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}
bool SLIsEmpty(pSL ps) {

	if (ps->size == 0) {

		return true;
	}
	else
		return false;
	}

void SLPushBack(pSL ps, SLDataType x) {
	SLCheckCapacity(ps);
	ps->a[ps->size++] = x;
}

void SLPushFront(pSL ps, SLDataType x) {
	SLCheckCapacity(ps);
	int end = ps->size - 1;
	while (end>=0)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[0] = x;
	ps->size++;
}
void SLPopBack(pSL ps) {
	assert(ps);
	assert(!SLIsEmpty(ps));
	ps->size--;
}

void SLPopFront(pSL ps) {
	assert(ps);
	assert(!SLIsEmpty(ps));
	int end = 0;
	while (end < ps->size-1)
	{
		ps->a[end] = ps->a[end + 1];
		end++;
	}
	ps->size--;
}
void SLInsert(pSL ps,int pos,SLDataType x) {
	assert(ps);
	SLCheckCapacity(ps);
	assert(pos >= 0 && pos <= ps->size);
	int end = ps->size - 1;
	while (end>=pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}

void SLErase(pSL ps, int pos) {
	assert(ps);
	assert(!SLIsEmpty(ps));
	assert(pos >= 0 && pos < ps->size);
	int end = pos;
	while (end<ps->size)
	{
		ps->a[end] = ps->a[end + 1];
		end++;
	}
	ps->size--;
}

int SLFind(pSL ps, SLDataType x	) {
	assert(ps);
	for (int i = 0; i < ps->size; i++) {
		if (ps->a[i] == x)
			return i;
	}
	return -1;

}
